package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.base.service.IUserService;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.alibaba.druid.sql.visitor.functions.If;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class CarPackageAuditImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IServiceItemService serviceItemService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectForList(qo);
        for (CarPackageAudit audit : carPackageAudits) {
            audit.setAuditor(userService.get(audit.getAuditorId()));
            audit.setServiceItem(serviceItemService.get(audit.getServiceItemId()));
        }
        return new TablePageInfo<CarPackageAudit>(carPackageAudits);
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateByInstanceId(Long id, String processInstanceId) {
        carPackageAuditMapper.updateByInstanceId(id, processInstanceId);
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit audit = this.get(id);
        InputStream inputStream = null;
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            inputStream = generator.generateDiagram(model, activeActivityIds,
                    Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");

        } else {
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST,
                    Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
        }
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有审核中的状态,才可以撤销");
        }
        // 修改服务单项状态为初始化
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        // 修改套餐审核记录为 撤销状态
        carPackageAuditMapper.changeStatus(id, CarPackageAudit.STATUS_CANCEL);
        // 删除运行中的实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "计划有变撤销流程");
    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        CarPackageAudit audit = this.get(id);
        if (audit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有审核中的需要审批");
        }
        String userName = ShiroUtils.getUser().getUserName();
        // 约定 2=同意
        if (auditStatus == 2) {
            info += "(" + userName + "同意)";
        } else {
            info += "(" + userName + "拒绝)";
        }
        audit.setInfo(audit.getInfo() + "<br>" + info);
        audit.setAuditTime(new Date());
        //执行当前节点
        Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        //设置审核操作的同意与否参数
        taskService.setVariable(task.getId(), "auditStatus", auditStatus);
        //设置审批备注
        taskService.addComment(task.getId(), audit.getInstanceId(), info);
        //执行节点审批
        taskService.complete(task.getId());
        // 获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();

        if (auditStatus == CarPackageAudit.STATUS_PASS) {
            if (nextTask != null) {
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));

            } else {
                //如果没有下个节点直接审核通过
                serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_APPROVED);
                audit.setStatus(CarPackageAudit.STATUS_REJECT);
            }
        } else {
            // 审核拒绝
            serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }
}
